package org.piwicode.bywordofmouth.net;

import com.google.common.base.Preconditions;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;

/**
 *
 * @author pierre
 */
class ServerAcceptThread extends Thread {

    private final Service service;
    private final Executor executor;
    private final ServerSocket serverSocket;

    ServerAcceptThread(int port, Service service, final Executor executor) {
        this.service = Preconditions.checkNotNull(service);
        this.executor = Preconditions.checkNotNull(executor);
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                final Socket socket = serverSocket.accept();
                executor.execute(new ServerSocketRunnable(socket, service));
            }
        } catch (IOException ex) {
            //Result of socket.close();Allow thread to exit
        }
    }

    @Override
    public void interrupt() {
        try {
            serverSocket.close();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            super.interrupt();
        }
    }
}
